/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2015年5月14日         luwei
 */

package com.coocaa.x.service.liteuser;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.RemoteException;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.liteccconnector.LiteCCConnector;
import com.coocaa.x.service.liteuser.aidl.ILiteUserService;
import com.skyworth.webSDK.webservice.device.CamellisTVInfoDomain;
import com.skyworth.webSDK.webservice.device.CamellisTVInfoService;

public class LiteUserStub extends ILiteUserService.Stub {
    private Context mContext = null;
    private String mSession = "";

    public LiteUserStub(Context context) {
        this.mContext = context;
        IntentFilter filter = new IntentFilter();
        filter.addAction(LiteCCConnector.BROADCAST_CCC_ON_SESSION_UPDATE_ACTION);
        mContext.registerReceiver(mReceiver, filter);
        CoocaaApplication.post(new Runnable() {
            @Override
            public void run() {
                initSession();
            }
        });
    }


    @Override
    public void whoAmI() {
        LogUtils.d("wai", "<<LiteUserService>> who am i??  " + mContext.getPackageName());
    }

    public void initSession() {
        try {
            mSession = XServiceManager.getLiteCCConnectorService().getUserSession();
            LogUtils.d("session", "initsession and get session from service is " + mSession);
            if (mSession.equals(LiteCCConnector.ERRORCODE_SESSION_NOT_EXIST)) {
                mSession = getDeviceSession();
                LogUtils.d("session", "initsession and get session by device is " + mSession);
            }
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(LiteCCConnector.BROADCAST_CCC_ON_SESSION_UPDATE_ACTION)) {
                String session = intent.getExtras().getString(
                        LiteCCConnector.BROADCAST_CCC_ON_SESSION_UPDATE_EXTRA_SESSION);
                LogUtils.d("session", "receive session is " + session);
                if (!session.equals(LiteCCConnector.ERRORCODE_SESSION_NOT_EXIST)
                        && !session.equals(LiteCCConnector.ERRORCODE_SESSION_NOT_LOADED)) {
                    mSession = session;
                }
            }
        }
    };

    @Override
    public synchronized String getSession() throws RemoteException {
        if (mSession.equals("")) {
            initSession();
        }
        if (mSession.equals(LiteCCConnector.ERRORCODE_SESSION_NOT_EXIST)
                || mSession.equals(LiteCCConnector.ERRORCODE_SESSION_NOT_LOADED)) {
            mSession = "";
        }
        LogUtils.d("session", "session:" + mSession);
        return mSession;
    }

    private synchronized String getDeviceSession() {
        // String session = AppSharePreference.getInstance().getStringValue("session", "");
        // if (session != null && !session.equals(""))
        // {
        // LogUtils.d("session", "getDeviceData  session :" + session);
        // return session;
        // }
        while (!Android.isNetConnected(mContext)) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            LogUtils.d("waiting for network!!");
        }
        String session = null;
        String sdk = android.os.Build.VERSION.SDK;
        String model = android.os.Build.MODEL;
        String mac = CoocaaApplication.getMAC();
        Display display = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay();
        int W = display.getWidth();
        int H = display.getHeight();
        LogUtils.d("session", "getDeviceData sdk:" + sdk + " model:" + model + " mac:" + mac + " width:"
                + W + " height:" + H);
        CamellisTVInfoDomain domain = new CamellisTVInfoDomain();
        domain.setMac(mac);
        domain.setWidth(String.valueOf(W));
        domain.setHeight(String.valueOf(H));
        domain.setModel(model);
        domain.setSdk(sdk);
        if (mac != null && !mac.equals(""))
            session = getSessionByDevices(domain);
        if (session.equals(""))
            session = "";
        return session;
    }

    private String getSessionByDevices(CamellisTVInfoDomain domain) {
        CamellisTVInfoService ss = new CamellisTVInfoService("tc.skysrt.com");// tc.skysrt.com ,
        // 121.199.33.2:8081
        String session = ss.submitTVInfo2Camellis(domain);
        LogUtils.d("session", "getSessionByDevices---session:" + session);
        if (session != null && !session.equals(""))
            try {
                XServiceManager.getLiteConfigService().saveStringConfig("session", session);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        return session;
    }

    public void destory() {
        mContext.unregisterReceiver(mReceiver);
    }
}
